var xhr;
var xhr2;
$("#key").keyup(function (){
   // var xhr;
    var keyword=$(this).val();
    if(keyword==""){
        $("#context1").css("display","none");     //列表不展示新的东西
        return ;
    }
    xhr=new XMLHttpRequest();
    xhr.onreadystatechange=fun1;
    xhr.open("GET","browse?action=autoComplete&keyword="+keyword,true);
    xhr.send(null);
}
)
function fun1(){
    if(xhr.readyState===4){
        if(xhr.status===200){
            var content=xhr.responseText;
            var res=content.split(",");
            var html="";
            var name=['FISH','DOGS','REPTILES','CATS','BIRDS'];
            var num=[0,0,0,0,0];
            for(var j=0;j<5;j++){
                for(var i=0;i<res.length;i++){
                    var product=res[i].split("?");
                    if(res[i]!=''&&res[i]!="NONE" &&product[1]===name[j]){
                        if(num[j]===0){
                            html+="<div style='font-weight: bold;height: 25px;font-size: 20px;border: 1px solid gray;background-color: lightskyblue;text-align: center' >"+name[j]+"</div>";
                        }
                        html+="<div style='padding-left: 3px' onclick = 'setSearch_onclick(this)' " +
                            "onmouseout='changeBackColor_out(this)' " +
                            "onmouseover='changeBackColor_over(this)'>"
                            +product[0]+"</div>";
                        res[i]="NONE";
                        num[j]=1;
                    }
                }
            }
            $("#context1").html(html);
            //显示为块级元素
            if(res.length!=0&&res[0]!=""){
                $("#context1").css("display","block");
            }else{
                $("#context1").css("display","none");
            }
        }
    }
}

//鼠标移动到内容上：
function changeBackColor_over(div){
    $(div).css("background-color","#CCCCCC");
}
//鼠标离开内容
function changeBackColor_out(div){
    $(div).css("background-color","#FFFFFF");
}
//将点击的内容放到搜索框内
function setSearch_onclick(div){
    console.log("点击事件发生+++++++++");
    $("#key").val(div.innerText);
    $("#context1").css("display","none");
    //-------------------------开始实现点击跳转功能
    var name=div.innerText;
    console.log("name:"+name);
    xhr2=new XMLHttpRequest();
    xhr2.onreadystatechange=fun2;
    xhr2.open("GET","browse?action=add&productName="+name,true);    //设为异步请求
    xhr2.send(null);
}

function fun2(){
    if(xhr2.readyState===4){
        if(xhr2.status===200){
            var text=xhr2.responseText;
            console.log(text);
            window.location.href="browse?action=viewProduct&productId="+xhr2.responseText;
        }
    }
}
